#include "server_main.h" // IWYU pragma: keep
#include "server_library_object.h"
#pragma comment(lib, "ws2_32.lib")

int main() {
   // Initialize the server
   // 设置中文编码环境
#if defined(_WIN32) || defined(_WIN64)
   setlocale(LC_ALL, ".65001");
#else
   setlocale(LC_ALL, "zh_CN.UTF-8");
#endif
   // 日志系统初始化
   server_log_init(LOG_OUTPUT_TYPE_FILE);
   server_log(LOG_SYSTEM,"Server Starting...\n");
   // 加载服务器配置文件
   // server_load_config(); // 改过了得重新弄
   // 读取图书馆物品数据
   if (server_load_object_data() != 0) {
      server_log(LOG_SYSTEM,"Failed to load library object data.\n");
      return 1; // 加载失败，退出程序
   }
   // 初始化服务器通信模块
   if (server_correspond_init() != 0) {
      server_log(LOG_SYSTEM,"Failed to initialize server communication.\n");
      return 1; // 初始化失败，退出程序
   }
   // 服务器通信事件处理
   server_log(LOG_SYSTEM,"Server communication initialized.\n");
   // 服务器通信事件循环
   while (1) {
      SOCKET client_socket = server_correspond_accept_socket(); // 接受客户端连接
      if (client_socket == INVALID_SOCKET) {
         continue; // 接受失败，继续循环
      }
      char client_ip[INET_ADDRSTRLEN]; // 存储客户端IP地址
      struct sockaddr_in client_addr;
      socklen_t addr_len = sizeof(client_addr);
      if (getpeername(client_socket, (struct sockaddr *)&client_addr, &addr_len) == 0) {
         inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip)); // 获取客户端IP地址
      } else {
         strcpy(client_ip, "Unknown"); // 如果获取失败，设置为未知
      }
      server_log(LOG_SYSTEM,"Client connected from IP: %s\n", client_ip);
      // 处理客户端请求
      server_correspond_event_handler(client_socket, client_ip); // 处理客户端请求
      closesocket(client_socket); // 关闭客户端Socket
      server_log(LOG_SYSTEM,"Client disconnected from IP: %s\n", client_ip);
   }
   WSACleanup();
   // 保存图书馆物品数据
   server_save_object_data();
   server_save_config();
   server_log(LOG_SYSTEM,"Server Init Success.\n");
   server_log(LOG_SYSTEM,"Server Closed.\n");

   return 0;
}
